#include "DeviceManager.h"

template<> DeviceManager* Ogre::Singleton<DeviceManager>::ms_Singleton = 0;

DeviceManager::DeviceManager(Ogre::RenderWindow* mWindow) :
	mInputManager(0),
	mMouse(0),
	mKeyboard(0),
	mMouseCursor(0),
	mUseBufferedInputKeys(true),
	mUseBufferedInputMouse(true)
{
	// Initialize mouse and keyboard
	OIS::ParamList pl;
	size_t windowHnd = 0;
	std::ostringstream windowHndStr;

	mWindow->getCustomAttribute("WINDOW", &windowHnd);
	windowHndStr << windowHnd;
	pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));

	mInputManager = OIS::InputManager::createInputSystem( pl );

	mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, mUseBufferedInputKeys ));
	mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, mUseBufferedInputMouse ));

	// Register MouseCursor to user over CEGUI's
	mMouseCursor = new MouseCursor();
    mMouseCursor->setVisible(true);
    mMouseCursor->setWindowDimensions(mWindow->getWidth(), mWindow->getHeight());
}

DeviceManager::~DeviceManager()
{
	if (mInputManager)
	{
		mInputManager->destroyInputObject( mMouse );
		mInputManager->destroyInputObject( mKeyboard );

		OIS::InputManager::destroyInputSystem(mInputManager);
		mInputManager = 0;

		if (mMouseCursor) delete mMouseCursor;
		mMouseCursor = 0;
	}
}

void DeviceManager::setBuffered(bool isBuffered)
{
	mUseBufferedInputKeys = isBuffered;
	mUseBufferedInputMouse = isBuffered;
	mKeyboard->setBuffered(isBuffered);
	mMouse->setBuffered(isBuffered);
	if (isBuffered)	mMouseCursor->setVisible(true);
	else mMouseCursor->setVisible(false);
}